from datetime import datetime

from werkzeug.urls import url_parse

from app import app, db
import os
from flask import render_template, flash, redirect, url_for, session, request

from app.email import send_password_reset_email
from passlib.hash import sha256_crypt
from functools import wraps
import time
from app.forms import RegistrationForm, LoginForm, ResetPasswordRequestForm, EditProfileForm, ResetPasswordForm
from app.forms import RegistrationForm, LoginForm
from app.forms import RegistrationForm, LoginForm, ResetPasswordRequestForm, ArticleForm
from app.forms import RegistrationForm, LoginForm, EditProfileForm
from flask import send_from_directory
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User, Post


@app.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()

#2个路由
@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html')


@app.route('/login',methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    login_form = LoginForm()
    if login_form.validate_on_submit():
        user = User.query.filter_by(username=login_form.username.data).first()
        if user is None or not user.check_password(login_form.password.data):
            flash('invalid username or pwd')

        login_user(user, login_form.remember_me.data)
        next_page =request.args.get('next')
        if not next_page or url_parse(next_page).netloc!='':
            next_page = url_for('index')
        return redirect(next_page)


        return redirect(url_for('index'))
    return render_template('login.html', title='login', form=login_form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/register',methods=['GET','POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user =User(username=form.username.data,email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations,you are now a register user!')
        return redirect(url_for('login'))
    return render_template('register.html',title ='Register',form=form)

@app.route('/user/<username>')
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    posts = [

    ]
    return render_template('user.html', user=user, posts=posts)

@app.route('/edit_profile',methods=['GET','POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        db.session.commit()

        flash('Your changes have been saved.')
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', title='Edit_Profile', form=form)

@app.route('/notes',methods=['GET','POST'])
@login_required
def notes():
    #print(current_user)
    name = current_user.username
    user = User.query.filter_by(username=name).first()
    posts =Post.query.filter_by(user_id = user.id).all()


    if posts:
        return render_template('articles.html',articles = posts,username =name)
    else:
        msg ="暂无笔记！"
        return render_template('articles.html',msg=msg)


@app.route('/reset_password_request',methods=['GET','POST'])
def reset_password_request():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = ResetPasswordRequestForm()
    if form.validate_on_submit():
        user =User.query.filter_by(email=form.email.data).first()
        if user:
            send_password_reset_email(user)
        flash("发送成功，注意查收！", "success")
        return redirect(url_for('login'))
    return render_template('reset_password_request.html',title='Reset Password',form=form)
@app.route('/reset_password/<token>',methods=['GET','POST'])
def reset_password(token):
    if current_user.is_authenticated:
        return  redirect(url_for('index'))
    user =User.verify_reset_password_token(token)
    if  not user:
        return redirect((url_for('index')))
    form= ResetPasswordForm()
    if form.validate_on_submit():
        user.set_password(form.password.data)
        db.session.commit()
        flash('Your password has been reset.')
        return redirect(url_for('login'))
    return render_template('reset_password.html',form=form)







@app.route('/add_article', methods=['GET', 'POST'])
@login_required
def add_article():
    form = ArticleForm(request.form)  # 实例化ArticleForm表单类
    if request.method == 'POST' and form.validate():  # 如果用户提交表单，并且表单验证通过
        # 获取表单字段内容
        t = form.title.data
        content = form.content.data
        author = current_user.username
        user = User.query.filter_by(username=author).first_or_404()

        new_post = Post(title=t,body=content,user_id=user.id)
        db.session.add(new_post)
        db.session.commit()
        #print(title + content+author+create_date)
        flash('创建成功', 'success')  # 闪存信息
        return redirect(url_for('index'))  # 跳转到控制台
    return render_template('add_article.html', form=form)  # 渲染模板

# 编辑笔记
@app.route('/edit_article/<string:id>', methods=['GET', 'POST'])
@login_required
def edit_article(id):
    this_id =id
    name = current_user.username
    user = User.query.filter_by(username=name).first_or_404()
    post = Post.query.filter_by(id=id).first_or_404()
    #print(user)
    article = Post.query.filter_by(id=this_id).first_or_404() # 查找一条记录
    # 检测笔记不存在的情况
    if not article:
        flash('ID错误', 'danger') # 闪存信息
        return redirect(url_for('index'))
   #检验权限
    if (user.id!= post.user_id):
        flash("你没有权限编辑该笔记",'danger')
        return redirect(url_for('index'))
    # 获取表单
    form = ArticleForm(request.form)
    if request.method == 'POST' and form.validate(): # 如果用户提交表单，并且表单验证通过
        # 获取表单字段内容
        title = request.form['title']
        content = request.form['content']
        now = Post.query.filter_by(id=this_id).first_or_404()
        now.body=content
        now.title=title
        db.session.commit()
        flash("your commit will be rejected!", 'success')


    form.title.data=article.title
    form.content.data=article.body
    # 从数据库中获取表单字段的值
    return render_template('edit_article.html', form=form,post=post) # 渲染模板

@app.route('/article/<string:id>')
@login_required
def article(id):
    this_id =id

    ace= Post.query.filter_by(id=this_id).first()
    name = User.query.filter_by(id=ace.user_id).first()
    #print(ace.body)
    return render_template('article.html', article=ace,username= name.username) # 渲染模板


